package com.thymeleaf.demo.lib;

import com.thymeleaf.demo.util.Common;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;

@Component
public class AdminLib {

    @Autowired
    Common common;

    /**
     * 获取密码
     * @return
     */
    public String getPwd(String pwd, String salt){
        return common.md5(pwd + salt);
    }

    /**
     * 设置密码
     * @return
     */
    public<T> T setPwd(String pwd, Class<T> classes, T object) throws Exception {
        // 密码盐
        String salt = common.getRandomString(6, 3);
        // 加密后的密码
        pwd = getPwd(pwd, salt);
        // 通过反射设置类中的值
        Field field = classes.getDeclaredField("pwd");
        field.setAccessible(true);
        field.set(object, pwd);

        field = classes.getDeclaredField("salt");
        field.setAccessible(true);
        field.set(object, salt);

        return object;
    }
}
